﻿using IndustrialControlLibrary.Utils;
using Modbus.Device;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace IndustrialControlLibrary
{
    public partial class HMI_I_Input : UserControl
    {
        public HMI_I_Input()
        {
            InitializeComponent();
        }


        private bool _isAssigned = false;
        public dynamic modbusMaster;

        public byte slaveAddress;
        public byte funcCode;
        public ushort registerAdderss;

        /// <summary>
        /// 将建立好的链接传入控件
        /// </summary>
        /// <param name="connetionMaster"></param>
        public void assignMaster(dynamic connetionMaster)
        {
            modbusMaster = connetionMaster;
            _isAssigned = true;
            string[] _stringAddress = this.Address.Split(':');
            slaveAddress = Convert.ToByte(_stringAddress[0]);
            registerAdderss = (ushort)(Convert.ToInt32(_stringAddress[1].Remove(0, 1)) - 1);
        }


        private void btn_write_Click(object sender, EventArgs e)
        {
            if (this.textBox1.Text != null && _isAssigned)
            {
                ushort value;
                if (this.NumType == NumType.ushort_16)
                {
                    value = Convert.ToUInt16(this.textBox1.Text);
                }
                else
                {
                    var ret = Convert.ToInt16(this.textBox1.Text);
                    value = (ushort)ret;
                }
                modbusMaster.WriteSingleRegister(slaveAddress, registerAdderss, value);
            }
        }
    }
}
